﻿using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using ThinkDotNetBotApiCommon.Weapons;
using ThinkDotNetEngine.Bots.Ammos;

namespace ThinkDotNetEngine.Bots.Weapons
{
    [XmlInclude(typeof(PlasmaWeapon))]
    [XmlInclude(typeof(RocketWeapon))]
    [XmlInclude(typeof(TacticalMissileWeapon))]
    public abstract class WeaponBase:IWeaponBase
    {        
        #region Constructors

        protected WeaponBase()
        {
        }
        protected WeaponBase(TankBot owner,WeaponBase weaponBase,IAmmoLoader ammoLoader,IAmmoHandler ammoHandler)
        {
            Owner = owner;
            _ammoHandler = ammoHandler;
            LaunchTime = weaponBase.LaunchTime;
            AmmoLoader = ammoLoader;
        }

        #endregion
        
        #region Public Methods

        public abstract AmmoBase CreateAmmo();

        public bool Launch(Vector3 direction, params Vector3[] startPositions)
        {
            if (!_ammoHandler.CanBeLaunched(_lastLaunch, LaunchTime))
                return false;

            foreach (var starPosition in startPositions)
            {
                AmmoBase ammo = CreateAmmo();
                ammo.Weapon = this;
                ammo.CurrentPosition = starPosition;
                ammo.CurrentDirection = direction;
                GameTime lastLaunchGameTime = _ammoHandler.AddAmmo(ammo);
                _lastLaunch = lastLaunchGameTime.TotalGameTime.TotalMilliseconds;
            }
            return true;
        }

        #endregion

        #region Protected Methods
   
        #endregion

        #region Fields

        private double _lastLaunch = double.MinValue;
        private readonly IAmmoHandler _ammoHandler;

        #endregion

        #region Properties

        public int LaunchTime { get; set; }

        [XmlIgnore]
        public IAmmoLoader AmmoLoader { get; private set; }
        [XmlIgnore]
        public TankBot Owner { get; private set; }
        

        #endregion
    }
}
